package com.aiyige.page.my.customer;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiHelper;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventCustomerFollowupAddSuccess;
import com.aiyige.model.Subject;
import com.aiyige.model.request.CustomerAddFollowupRequest;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.my.customer.adapter.IntentionalProductAdapter;
import com.aiyige.page.my.customer.dialog.CheckboxBottomDialog;
import com.aiyige.page.my.customer.model.CheckboxSelectionEntity;
import com.aiyige.page.my.customer.model.CustomerEntity;
import com.aiyige.page.my.customer.model.CustomerFollowupEntity;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ColorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.MyLayoutManager;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.TimePickerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 客户管理筛选
 * Created by xiachao on 2018/3/26.
 */
@Track("添加跟进页")
@Route(path = ARouterConfig.AddFollowUpPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class AddFollowUpPage extends BaseActivity {

    @Autowired
    CustomerEntity customer;
    @BindView(R.id.fl_intentional_product)
    FrameLayout flIntentionalProduct;
    @BindView(R.id.rv_intentional_product)
    RecyclerView rvIntentionalProduct;
    IntentionalProductAdapter adapter;
    @BindView(R.id.fl_recyclerView)
    FrameLayout flRecyclerViewt;

    @BindView(R.id.et_follow_up_content)
    EditText etFollowUpContent;
    @BindView(R.id.et_next_follow_up_content)
    EditText etNextFollowUpContent;

    @BindView(R.id.tv_intentional_product)
    TextView tvIntentionalProduct;
    @BindView(R.id.tv_next_follow_up_time)
    TextView tvNextFollowUpTime;

    @BindView(R.id.tv_max_this_content)
    TextView tvMaxThisContent;
    @BindView(R.id.tv_max_next_content)
    TextView tvMaxNextContent;


    InputNumFilter inputNumFilterThisContent;
    InputNumFilter inputNumFilterNextContent;
    long nextFollowupTime;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_customer_add_follow_up);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        initView();
    }


    private void initView() {
        MyLayoutManager linearLayoutManagerTop = new MyLayoutManager();
        linearLayoutManagerTop.setAutoMeasureEnabled(true);
        adapter = new IntentionalProductAdapter();
        rvIntentionalProduct.setLayoutManager(linearLayoutManagerTop);
        rvIntentionalProduct.setAdapter(adapter);
        inputNumFilterThisContent = new InputNumFilter(500);
        inputNumFilterThisContent.setListener(new InputNumFilter.Listener() {
            @Override
            public void inputNum(int num) {
                tvMaxThisContent.setText(getResources().getString(R.string.text_max, num + "", 500 + ""));
            }
        });
        etFollowUpContent.setFilters(new InputFilter[]{inputNumFilterThisContent});

        inputNumFilterNextContent = new InputNumFilter(500);
        inputNumFilterNextContent.setListener(new InputNumFilter.Listener() {
            @Override
            public void inputNum(int num) {
                tvMaxNextContent.setText(getResources().getString(R.string.text_max, num + "", 500 + ""));
            }
        });
        etNextFollowUpContent.setFilters(new InputFilter[]{inputNumFilterNextContent});
        tvMaxThisContent.setText(getResources().getString(R.string.text_max, 0 + "", 500 + ""));
        tvMaxNextContent.setText(getResources().getString(R.string.text_max, 0 + "", 500 + ""));
        fillIntentionalList();
    }

    private void doRequest() {
        if (ListUtil.isEmpty(adapter.getData())) {
            ToastX.show(getStr(R.string.intentional_product_can_not_empty));
            return;
        }
        if (TextUtils.isEmpty(etFollowUpContent.getText().toString().trim())) {
            ToastX.show(getStr(R.string.follow_up_content_can_not_empty));
            return;
        }
//        if (nextFollowupTime <= 0) {
//            ToastX.show(getStr(R.string.next_follow_up_time_can_not_empty));
//            return;
//        }
//        if (TextUtils.isEmpty(etNextFollowUpContent.getText().toString().trim())) {
//            ToastX.show(getStr(R.string.next_follow_up_content_can_not_empty));
//            return;
//        }
        String intentionalProductContent = null;
        for (CheckboxSelectionEntity entity : adapter.getData()) {
            if (intentionalProductContent == null) {
                intentionalProductContent = entity.getName();
            } else {
                intentionalProductContent = intentionalProductContent + "/" + entity.getName();
            }
        }
        CustomerFollowupEntity customerFollowUpEntity = CustomerFollowupEntity.newBuilder().
                customerId(customer.getId())
                .followuperId(AccountUtil.getCurrentUser().getId())
                .interestProduct(intentionalProductContent)
                .followupContent(etFollowUpContent.getText().toString().trim())
                .nextFollowupTime(nextFollowupTime)
                .nextFollowupContent(etNextFollowUpContent.getText().toString().trim()).build();
        showLoading();
        CustomerAddFollowupRequest.newBuilder().followupEntity(customerFollowUpEntity).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    hideLoading();
                    if (response.isSuccessful()) {
                        CustomerFollowupEntity customer = JsonUtil.toObject(response.body().string(), CustomerFollowupEntity.class);
                        if (customer != null) {
                            EventBus.getDefault().post(EventCustomerFollowupAddSuccess.newBuilder().customerRequestModel(customer).build());
                            ToastX.show(getStr(R.string.add_success));
                        }
                        finish();
                    } else {
                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                        if (data != null) {
                            ToastX.show(data.getMessage());
                        }
                    }
                } catch (Exception e) {
                    ApiHelper.getInstance().failed(this, call, response, e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                hideLoading();
                if (t != null) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    @OnClick({R.id.fl_intentional_product, R.id.titleBackBtn, R.id.btn_finish, R.id.fl_next_follow_up_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fl_intentional_product:
                CheckboxBottomDialog checkboxBottomDialog = CheckboxBottomDialog.newInstance();
                List<CheckboxSelectionEntity> list = new ArrayList<>();
                list.add(CheckboxSelectionEntity.newBuilder().name(Subject.getSubjectName(Subject.video_course))
                        .selected(isSelect(Subject.getSubjectName(Subject.video_course))).build());
                list.add(CheckboxSelectionEntity.newBuilder().name(Subject.getSubjectName(Subject.major_course))
                        .selected(isSelect(Subject.getSubjectName(Subject.major_course))).build());
//                list.add(CheckboxSelectionEntity.newBuilder().name(Subject.getSubjectName(Subject.training_course))
//                        .selected(isSelect(Subject.getSubjectName(Subject.training_course))).build());
//                list.add(CheckboxSelectionEntity.newBuilder().name(Subject.getSubjectName(Subject.training_card))
//                        .selected(isSelect(Subject.getSubjectName(Subject.training_card))).build());

                checkboxBottomDialog.setData(list);
                checkboxBottomDialog.setTitle(getStr(R.string.intentional_product_selection));
                checkboxBottomDialog.setLisenter(new CheckboxBottomDialog.Listener() {
                    @Override
                    public void onSelect(List<CheckboxSelectionEntity> selectedList) {
                        adapter.setNewData(selectedList);
                        fillIntentionalList();
                    }
                });
                checkboxBottomDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.btn_finish:
                doRequest();
                break;
            case R.id.fl_next_follow_up_time:
                Calendar selectedDate = Calendar.getInstance();
                Calendar startDate = Calendar.getInstance();
                startDate.set(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH), startDate.get(Calendar.DAY_OF_MONTH),
                        startDate.get(Calendar.HOUR_OF_DAY), startDate.get(Calendar.MINUTE));
                if (AccountUtil.getCurrentUser().getMoreBackup().getBirthDate()!=null&&AccountUtil.getCurrentUser().getMoreBackup().getBirthDate() != 0) {
                    selectedDate.setTimeInMillis(AccountUtil.getCurrentUser().getMoreBackup().getBirthDate());
                }
                Calendar endDate = Calendar.getInstance();
                endDate.set(startDate.get(Calendar.YEAR) + 10, startDate.get(Calendar.MONTH), startDate.get(Calendar.DAY_OF_MONTH),
                        startDate.get(Calendar.HOUR_OF_DAY), startDate.get(Calendar.MINUTE));
                //时间选择器
                TimePickerView pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        nextFollowupTime = date.getTime();
                        tvNextFollowUpTime.setText(TimeUtils.dateToYYYYMMDDHHMM(nextFollowupTime));
                    }
                })
                        //年月日时分秒 的显示与否，不设置则默认全部显示
                        .setType(new boolean[]{true, true, true, true, true, false})
                        .setSubmitText(getString(R.string.finish))
                        .setTitleBgColor(Color.WHITE)
                        .setBgColor(0xfff0f0f0)
                        .setLabel("", "", "", "", "", "")
                        .isCenterLabel(false)
                        .setDividerColor(Color.DKGRAY)
                        .setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setContentSize(21)
                        .setDate(selectedDate)
                        .setRangDate(startDate, endDate)
                        .isDialog(true)
                        .build();
                pickerView.show();
                break;
        }
    }

    private void fillIntentionalList() {
        ViewGroup.LayoutParams layoutParams = flRecyclerViewt.getLayoutParams();
        if (ListUtil.isEmpty(adapter.getData())) {
            layoutParams.height = 0;
        } else {
            layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        }
        flRecyclerViewt.setLayoutParams(layoutParams);
    }

    private boolean isSelect(String name) {
        boolean isSelected = false;
        List<CheckboxSelectionEntity> list = adapter.getData();
        if (ListUtil.isEmpty(list)) {
            return false;
        }
        for (CheckboxSelectionEntity listEntity : list) {
            if (listEntity.getName().equals(name)) {
                return true;
            }
        }
        return isSelected;
    }

    private String getStr(int stringId) {
        return getResources().getString(stringId);
    }


}
